// pages/others/list/list.js
var app     = getApp();//获取全局注册函数
var utils = require('../../utils/util.js');
var base64Js = require('../../utils/base64.js');
var md5Js = require('../../utils/md5.js');
var object = {};
object.data =  {
    list: [],
    total_price:0,
    order_list:'',
    allStatus: false,
    item:{selectStatus:true}
}
object.onLoad = function(){
    wx.switchTab({url: '../cart/cart',}); 
    //获取缓存
    var cart_items_cache = wx.getStorageSync('cart_info');
    console.log(123);
    console.log(cart_items_cache);
    console.log(456);
    this.setData({list: cart_items_cache, item: {selectStatus: true}});
    // 页面初始化 options为页面跳转所带来的参数
}
//去结算
object.postOrder = function(e){
  try{
    var order_list = e.target.dataset.order_list;
    var user_info  = wx.getStorageSync('user_info');
    if(order_list){
      var parms_url  = app.request_url+'C_Order?';
      var payload_str = 'orderList='+order_list;
      var request_data = user_info.user_itmes;
      var uid         = request_data.id.toString();
      var private_key = user_info.private_key;
      var t           =  new Date().getTime().toString();
      var payload = base64Js.encode(payload_str);
      console.log(payload);
      var k = md5Js.hex_md5(private_key+t+payload);
      parms_url += '&uid='+request_data.id;
      parms_url += '&userType='+request_data.type;
      parms_url += '&t='+t;
      parms_url += '&k='+k;
      parms_url += '&v='+app.version;
      console.log(parms_url);
      wx.request({
        url: parms_url,
        method: 'POST',
        data:{payload:payload},
        header: {
              'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res){
          var respones = res;
          if((respones.statusCode=='200')&&(respones.data.Success==1)){
                //登录成功
                var user_items = respones.data.CallInfo;
                //d调用异步存储api将用户信息写进缓存
                wx.setStorage({
                  key: 'order_info',
                  data: {'order_info':user_items},
                  success: function(res){
                    wx.showToast({
                      title:'订单生成功',
                    });
                    setTimeout(function(){
                        wx.navigateTo({
                          url: '../orderPut/orderPut',
                        })
                    },1000)
                  },
                })
            }else{
              if(respones.data.ErrorMsg.indexOf('库存不足')){
                 wx.showModal({
                  title:'提示',
                  content:respones.data.ErrorMsg,
                  showCancel:false,
                  confirmColor:'black'
                })
              }else{
                 wx.showModal({
                  title:'提示',
                  content:'订单生成失败！',
                  showCancel:false,
                  confirmColor:'black'
                })
              }
            }
        },
        fail: function() {
          wx.showModal({
            title:'提示',
            content:'网络异常请求失败!',
            showCancel:false,
            confirmColor:'black'
         })    
        },
      })
    }
  }catch(e){
    console.log(e.message);
    return false;
    wx.showToast({
      title:'生成订单失败',
      icon:'loading'
    });
    console.log(e.message);return false;
  }
}
object.check = function(e){
   var index = e.currentTarget.dataset.index;
    this.data.list[index].selectStatus = true;
    this.setData({
      list: this.data.list
    });
}
object.uncheck = function(e){
  var index = e.currentTarget.dataset.index;
    this.data.list[index].selectStatus = false;
    this.setData({
      list: this.data.list
    });
}
object.selectAll = function(){
  var vm = this;
    var list = vm.data.list;
    for (var i = 0; i < list.length; i++) {
      if (!list[i].selectStatus) {
        vm.setData({
          allStatus: true
        });
        break;
      }
    }
    if (i >= list.length) {
      vm.setData({
        allStatus: false
      });
    }

    for (var i = 0; i < list.length; i++) {
      list[i].selectStatus = vm.data.allStatus;
    }
    //购买全部产品产品
    var cart_items = wx.getStorageSync('cart_info');
    var user_info  = wx.getStorageSync('user_info');
    var request_data = user_info.user_itmes;
    var cart_items_length = cart_items.length;
    if(cart_items_length){
        var order_list = '';
        var total = 0;
        var tmp = [];
        for(var i=0;i<cart_items_length;i++){
          order_list +=cart_items[i].product_id+';';
          order_list +=cart_items[i].cart_num+';';
          order_list +=request_data.channelId+';';
          order_list +=request_data.enterpriseId+';';
          order_list +=cart_items[i].sku_id+';'
          order_list +=cart_items[i].product_standard_id+',';
          tmp.push(this.Multiply(cart_items[i].sellprice,cart_items[i].cart_num));   
        }
    }
    var order_list_string =   order_list.substr(0,order_list.length-1);
    var total_price = 0;
    if(tmp.length>0){
        for(var j=0;j<tmp.length;j++){
            total_price = this.numAdd(tmp[j],total_price);
        }
    }else if(tmp.length==1){
        total_price = tmp[0];
    }
    console.log(total_price);
    vm.setData({
      list: list,
      total_price:total_price,
      order_list:order_list_string
    });
}
object.onReady = function(){
    // 页面初始化 options为页面跳转所带来的参数
}
object.onShow  = function(){
   wx.switchTab({url: '../cart/cart',}); 
    //获取缓存
    var cart_items_cache = wx.getStorageSync('cart_info');
    //console.log(cart_items_cache);return;
    this.setData({list:cart_items_cache});
    // 页面初始化 options为页面跳转所带来的参数
};
object.clearAll = function(){
  var that = this;
   wx.showModal({
     title:'提示',
     content:'确认清空购物车',
     success:function(res){
       wx.removeStorage({key: 'cart_info'})
         that.setData({total_price:0});
       wx.switchTab({url:'../index/index'})
     }
   });

   //
}
object.onHide = function(){
}
object.onUnload = function(){
  
}
object.Multiply =function(arg1, arg2){
    var m = 0; //扩大后的两数相乘比初始值相乘扩大的倍数
    var s1 = arg1.toString();
    var s2 = arg2.toString();

    try {
    //获取第一个参数的小数部分长度，去掉小数点后，小数部分的长度就是初始值的小数点右移的位数
    m += s1.split(".")[1].length;
    } catch (e) {
    }

    try {
    ////获取第二个参数的小数部分长度，去掉小数点后，小数部分的长度就是初始值的小数点右移的位数
    m += s2.split(".")[1].length;
    } catch (e) {
    }
    //返回值：将参数的小数点去掉然后相乘，最后除以Mah.pow(10,m)
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}
object.numAdd = function(num1, num2){
    var baseNum, baseNum1, baseNum2;
    try {
    baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
    baseNum1 = 0;
    }
    try {
    baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
    baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
}
Page(object);